package com.kll.tv.views

import android.content.Intent
import android.view.View
import android.widget.TextView
import com.google.gson.Gson
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.GetSystemMenuDetailResponse
import com.kll.carolinehmibiz.net.bean.GetSystemMenuResponse
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.listener.SecondaryMenuProtocol
import com.kll.carolinehmibiz.presentation.presenter.SecondaryMenuPresenter
import com.kll.tv.base.views.BaseActivity
import com.kll.tv.databinding.ActivitySecondaryMenuBinding
import com.kll.tv.utils.AppToast
import com.kll.carolinehmibiz.base.utils.L
import com.kll.tv.views.ui.HArticleFramLayout
import com.kll.tv.views.ui.VArticleFramLayout
import com.kll.tv.views.ui.listener.IArticleFramLayout

/**
 * 二级菜单页
 */
class SecondaryMenuActivity: BaseActivity<SecondaryMenuPresenter>(), SecondaryMenuProtocol.IView {
    private lateinit var binding: ActivitySecondaryMenuBinding
    private var tvMenus = arrayListOf<TextView>()
    private var mMenuDatas: ArrayList<GetSystemMenuResponse>? = null
    private var menuDetail: ArrayList<GetSystemMenuDetailResponse>? = null
    private var menuId = 0

    override fun initViewBinding(): View {
        binding = ActivitySecondaryMenuBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): SecondaryMenuPresenter {
        return SecondaryMenuPresenter(this, this)
    }

    override fun init() {
        menuId = intent.getIntExtra("menuId", 0)
        binding.tvTitle.text = intent.getStringExtra("menuTitle")!!

        tvMenus.add(binding.tvMenuTitle1)
        tvMenus.add(binding.tvMenuTitle2)
        tvMenus.add(binding.tvMenuTitle3)
        tvMenus.add(binding.tvMenuTitle4)
        tvMenus.add(binding.tvMenuTitle5)
        tvMenus.add(binding.tvMenuTitle6)
        tvMenus.add(binding.tvMenuTitle7)
        tvMenus.add(binding.tvMenuTitle8)

        loadData()
        initListener()
    }

    private fun loadData() {
        if (menuId != 0) {
            // 加载三级菜单
            mPresenter.loadSystemMenu(menuId)
            // 加载二级菜单详情
            mPresenter.getArticle(menuId)
        }
    }

    private fun initListener() {
        tvMenus.forEach {
            it.setOnClickListener {
                var index = tvMenus.indexOf(it)
                showMenusDetail(index)
            }
        }

        binding.ivBack.setOnClickListener {
            finish()
        }
        binding.ivBackCircular.setOnClickListener {
            finish()
        }
    }

    private fun showMenusDetail(index: Int) {
        if (mMenuDatas!![index].type == 1) {
            // 外链
            var intent = Intent()
            intent.setClass(this, ExternalLinksDetailsActivity::class.java)
//            intent.putExtra("url", mMenuDatas!![index].url)
            intent.putExtra("url", "http://www.baidu.com")
            intent.putExtra("menuTitle", mMenuDatas!![index].name)
            startActivity(intent)
        } else {
            // 内链
            when (mMenuDatas!![index].url) {
                "meirijiankzhishu" -> startActivity(Intent(this, HealthIndexActivity::class.java))
                "zizhuwenzhen" -> startActivity(Intent(this, SelfHelpConsultationActivity::class.java))
                "yuanchengyiliao" -> startActivity(Intent(this, FarDiagnosisActivity::class.java))
                else -> {
                    var intent = Intent()
                    intent.setClass(this, InternalLinksDetailsActivity::class.java)
                    intent.putExtra("menuId", mMenuDatas!![index].menu_id)
                    intent.putExtra("menuTitle", mMenuDatas!![index].name)
                    startActivity(intent)
                }
            }
        }
    }

    /**
     * 加载菜单成功
     */
    override fun getSystemMenuSuccessed(menus: ArrayList<GetSystemMenuResponse>) {
        mMenuDatas = menus
        L.d("TAG", "mMenuDatas: ${Gson().toJson(mMenuDatas)}")

        for(index in tvMenus.indices) {
            if(menus.size <= index) {
                tvMenus[index].visibility = View.GONE
            } else {
                tvMenus[index].visibility = View.VISIBLE
                tvMenus[index].text = menus[index].name
            }
        }
    }

    /**
     * 加载菜单失败
     */
    override fun getSystemMenuFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.loadSystemMenu(menuId)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 获取二级菜单详情成功
     */
    override fun getArticleSuccessed(data: ArrayList<GetSystemMenuDetailResponse>) {
        // 设置数据
         menuDetail = data

        // 文字
        if (menuDetail!![0].content_2!![0].type == 3) {
            binding.tvContent.text = "        "+menuDetail!![0].content_2!![0].url
        }

        // 图片
        var iv: IArticleFramLayout
        // template: 2-上下 1-左右 3-在内部链接详情页出现
        if(menuDetail!![0].template == 2) {
            iv = VArticleFramLayout(this)
            binding.flHeadArticle.addView(iv)
        } else {
            iv = HArticleFramLayout(this)
            binding.flHeadArticle.addView(iv)
        }

        iv.refreshUI(menuDetail!!)
    }

    /**
     * 获取二级菜单详情失败
     */
    override fun getArticleFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.getArticle(menuId)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

}